package se.ytterman.jpcap.data.integer;

import java.lang.*;
import java.io.*;
import java.util.regex.*;

import se.ytterman.jpcap.data.BinaryData;

public class ShortBinaryData extends BinaryData {

    public ShortBinaryData(int short_payload) {
	// Set byte value
	this.short_payload = (short_payload & 0xFFFF);
    }

    public ShortBinaryData(String shortValue) {
	// 
	String short_pattern = "(0[X|x][0-9|A-F]{1,4})";
	Pattern p = Pattern.compile(short_pattern);
	Matcher m = p.matcher(shortValue);

	// Perform basic check of format
	if(m.matches()) {
	    // Extract the hexadecimal digits
	    StringBuffer valueBuffer = new StringBuffer(shortValue);
	    String shortDigits = valueBuffer.substring(2);

	    // Assign byte value
	    this.short_payload = Integer.parseInt(shortDigits, 16); 
	}
	else {
	    // XXX Throw exception
	}
    }

    public ShortBinaryData(InputStream frameInputStream) throws Exception {
	// Read data from stream
	this.read(frameInputStream);
    }

    public int getShortInteger() {
	return this.short_payload;
    }

    public void read(InputStream frameInputStream) throws Exception {
	// Create a data input stream
	DataInputStream frameDataStream = 
	    new DataInputStream(frameInputStream);
	
	// Read an unsigned short from the stream
	this.short_payload = frameDataStream.readUnsignedShort();
    }

    public void write(OutputStream frameOutputStream) throws Exception {
	// Create a data output stream
	DataOutputStream frameDataStream = 
	    new DataOutputStream(frameOutputStream);
	
	// Write an unsigned short? (XXX) to the stream
	frameDataStream.writeShort(this.short_payload);
    }    

    public String toString() {
	String short_string = String.format("0X%04X", 
					   (this.short_payload & 0xFFFF));

	return short_string;
    }

    private int short_payload;
}
